import 'dart:async';
import 'dart:convert';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_is_know_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_more_menu_dialog/common_more_menu_dialog.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/terminal_num_update_event.dart';
import 'package:e_reception_flutter/media_library/media_library_index/media_library_index_view_model.dart';
import 'package:e_reception_flutter/media_library/media_library_index/widgets/share_poster_menu_dialog.dart';
import 'package:e_reception_flutter/singleton/share_repository/share_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/color_constants.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/bean/user_response_bean.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/ai_poster/ai_poster_diy_view_model.dart';
import 'package:e_reception_flutter/ui/ai_poster/edit_ai_poster_detail_page.dart';
import 'package:e_reception_flutter/ui/ai_poster/poster_push_settings_page.dart';
import 'package:e_reception_flutter/ui/index/bean/index_bind_termainal_info.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/widgets/bubble_widget.dart';
import 'package:e_reception_flutter/utils/file_utils.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/vg_widgets/annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_menu_widget/click_back_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_photo_preview/vg_photo_preview.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:sharesdk_plugin/sharesdk_defines.dart';
import 'package:sharesdk_plugin/sharesdk_map.dart';
import 'package:upgrade_flutter/upgrade_flutter.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_save_util_lib.dart';
import 'package:vg_base/vg_screen_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'ai_poster_index_response_bean.dart';
import 'ai_poster_psd_list_bean.dart';

class AiPosterDetailPage extends StatefulWidget {
  static const ROUTER = "AiPosterDetailPage";

  final AiPosterIndexListItemBean itemBean;

  const AiPosterDetailPage(
      {Key key,
        @required this.itemBean,
      })
      : assert(itemBean != null, "currentItem must be not null");

  @override
  State<StatefulWidget> createState() => _AiPosterDetailPageState();

  static Future<dynamic> navigatorPush(
      BuildContext context,
      AiPosterIndexListItemBean itemBean,) {
    return RouterUtils.routeForFutureResult(
        context,
        AiPosterDetailPage(
          itemBean: itemBean,
        ),
        routeName: AiPosterDetailPage.ROUTER);
  }
}

class _AiPosterDetailPageState extends BaseState<AiPosterDetailPage> {
  MediaLibraryIndexViewModel _viewModel;
  AiPosterDiyViewModel _diyViewModel;
  WebViewController _webViewController;
  String _downloadOrShare = "00"; //00下载，01分享, 02查看大图
  String _shareFlag = "00"; //00朋友圈 01好友

  //webview加载成功
  bool isUrlLoadComplete = false;
  bool showBubble = false;
  bool showDeleteBubble = false;
  bool canMirror = false;

  String _loadUrl;
  AiPosterIndexListItemBean _itemBean;
  ScrollController _horizontalController;
  List<AiPosterPsdListBean> _multiColorList;

  int _selectIndex = 0;
  ValueNotifier<int> _initPageNotifier;
  String _currentPsd;
  int _allTerminalSize = 0;
  StreamSubscription _terminalNumRefreshSubscription;
  @override
  void initState() {
    super.initState();
    // _webViewController?.loadUrl(getUrl(widget?.url));
    // loading(true, msg: "生成中");
    _itemBean = widget?.itemBean;
    List response = json.decode(_itemBean.psdurl);
    _multiColorList = List()..addAll(
        response.map((o) => AiPosterPsdListBean.fromMap(o))
    );

    _itemBean.htmlurl = "https://etpic.we17.com/template/html/diyPoster_detail.html";
    MediaLibraryIndexViewModel.EMPTY_FLAG = false;
    _viewModel = MediaLibraryIndexViewModel(this);
    _diyViewModel = AiPosterDiyViewModel(this);
    _horizontalController= ScrollController();
    _initPageNotifier = new ValueNotifier(_selectIndex);
    if(StringUtils.isNotEmpty(_itemBean?.diypicurl)){
      canMirror = true;
      if(StringUtils.isNotEmpty(_itemBean?.diypsd)){
        _setPsd(_itemBean?.diypsd);
      }
    }else{
      showBubble = true;
    }

    String cacheKey = UserRepository.getInstance().getHomePunchAndTerminalInfoCacheKey();
    ///获取缓存数据
    Future<String> future = SharePreferenceUtil.getString(cacheKey);
    future.then((jsonStr){
      if(!StringUtils.isEmpty(jsonStr)){
        setState(() {
          Map map = json.decode(jsonStr);
          IndexBindTermainalInfo bean = IndexBindTermainalInfo.fromMap(map);
          if(bean != null){
            if(bean.data != null
                && bean.data.bindTerminalList != null){
              _allTerminalSize = bean.data.bindTerminalList.length;
            }
          }
        });
      }
    });
    _terminalNumRefreshSubscription = VgEventBus.global.streamController.stream.listen((event) {
      if(event is TerminalNumRefreshEvent){
        _allTerminalSize = event?.num??0;
      }
    });
  }

  @override
  void dispose() {
    _terminalNumRefreshSubscription?.cancel();
    _initPageNotifier?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return  Scaffold(
      resizeToAvoidBottomPadding: false,
      resizeToAvoidBottomInset: false,
      backgroundColor: ColorConstants.BG_OR_SPLIT_COLOR,
      body: Stack(
        children: [
          Column(
              children:[
                _toTopBarWidget(),
                Expanded(
                  child: _toInfoWidget(),
                ),
                // SizedBox(height: ScreenUtils.getBottomBarH(context),)
              ]),
          Align(
            alignment: Alignment.topRight,
            child: Container(
              margin: EdgeInsets.only(top: ScreenUtils.getStatusBarH(context) + 44 - 6, right: 15),
              child: Visibility(
                visible: showBubble,
                child: BubbleWidget(
                    170.0,
                    39.0,
                    ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                    BubbleArrowDirection.top,
                    arrAngle: 85.0,
                    length: 134.0,
                    radius: 8.0,
                    arrHeight: 7.0,
                    strokeWidth: 0.0,
                    child: Text(
                        '编辑后可直接投屏播放',
                        style: TextStyle(
                            color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(), fontSize: 14.0
                        )
                    )
                ),
              ),
            ),
          ),
          // _toDeleteBubbleWidget(),
        ],
      ),
    );
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
        isShowBack: true,
        rightPadding: 15,
        rightWidget: Container(
          width: 110,
          child: Row(
            children: [
              GestureDetector(
                onTap: () {
                  CommonMoreMenuDialog.navigatorPushDialog(context,{
                    "删除":() async {
                      String title = "删除后不可恢复，确定删除该海报？";
                      if("01" == _itemBean?.useflg){
                        //如果有终端正在使用
                        title = "显示屏端的海报将同步删除，确定继续？";
                      }
                      bool result =
                      await CommonConfirmCancelDialog.navigatorPushDialog(context,
                          title: "提示",
                          content: title,
                          cancelText: "取消",
                          confirmText: "删除",
                          confirmBgColor: ThemeRepository.getInstance()
                              .getMinorRedColor_F95355());
                      if (result ?? false) {
                        _diyViewModel.deleteDiyPoster(context, _itemBean?.id, callback: (){
                          RouterUtils.pop(context);
                        });
                      }
                    }
                  });
                },
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 15),
                  child: Image.asset(
                    "images/icon_more_operations.png",
                    width: 20,
                  ),
                ),
              ),
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: (){
                  if(canMirror){
                    if(_allTerminalSize >= 1){
                      PosterPushSettingsPage.navigatorPush(context, _itemBean?.picid, _itemBean?.diypicurl, _itemBean?.id);
                    }else{
                      CommonISeeDialog.navigatorPushDialog(context, content: "暂无可投屏的显示屏");
                    }
                  }
                },
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(11.5),
                  child: Container(
                    width: 60,
                    height: 23,
                    alignment: Alignment.center,
                    color: canMirror?ThemeRepository.getInstance().getPrimaryColor_1890FF()
                        :ThemeRepository.getInstance().getLineColor_3A3F50(),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        canMirror?Image.asset(
                          "images/icon_can_mirror.png",
                          width: 11,
                          height: 13,
                          fit: BoxFit.contain,
                        ):Image.asset(
                          "images/icon_un_mirror.png",
                          width: 11,
                          height: 13,
                          fit: BoxFit.contain,
                        ),
                        SizedBox(width: 4,),
                        Text(
                          "投屏",
                          style: TextStyle(
                              fontSize: 12,
                              color: canMirror?Colors.white:ThemeRepository.getInstance().getHintGreenColor_5E687C(),
                              height: 1.2
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        )
    );
  }


  Widget _toDeleteBubbleWidget(){
    return Visibility(
      visible: showDeleteBubble,
      child: Positioned(
        top: 0,
        bottom: 0,
        left: 0,
        right: 0,
        child: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: (){
            setState(() {
              showDeleteBubble = !showDeleteBubble;
            });
          },
          child: Container(
            color: Colors.transparent,
            child: Stack(
              children: [
                Positioned(
                    top: ScreenUtils.getStatusBarH(context) + 44 - 6,
                    right: 75,
                    child: BubbleWidget(
                        120.0,
                        65.0,
                        ThemeRepository.getInstance().getLineColor_3A3F50(),
                        BubbleArrowDirection.top,
                        arrAngle: 85.0,
                        length: 84.0,
                        radius: 12.0,
                        arrHeight: 6.0,
                        strokeWidth: 0.0,
                        child: GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: ()async{
                            setState(() {
                              showDeleteBubble = !showDeleteBubble;
                            });
                            String title = "删除后不可恢复，确定删除该海报？";
                            if("01" == _itemBean?.useflg){
                              //如果有终端正在使用
                               title = "显示屏端的海报将同步删除，确定继续？";
                            }
                            bool result =
                            await CommonConfirmCancelDialog.navigatorPushDialog(context,
                                title: "提示",
                                content: title,
                                cancelText: "取消",
                                confirmText: "删除",
                                confirmBgColor: ThemeRepository.getInstance()
                                    .getMinorRedColor_F95355());
                            if (result ?? false) {
                              _diyViewModel.deleteDiyPoster(context, _itemBean?.id, callback: (){
                                RouterUtils.pop(context);
                              });
                            }
                          },
                          child:  SizedBox(
                            height: 45,
                            width: 120.0,
                            child: Center(
                              child: Text(
                                  '删除',
                                  style: TextStyle(
                                      color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(), fontSize: 14.0
                                  )
                              ),
                            ),
                          ),
                        )
                    )
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  ///内容布局
  Widget _toInfoWidget() {
    return Column(
      children: [
        SizedBox(height: 10,),
        _toWebViewWidget(),
        // (("01" == _itemBean?.colorflg) && _multiColorList != null && _multiColorList.length != 0)?SizedBox(height: 15,):SizedBox(height: 0,),
        // _getHorizontalList(),
        Expanded(
          child: _toBottomWidget(),
        ),
      ],
    );
  }

  Widget _toWebViewWidget() {
    double maxHeight = ScreenUtils.screenH(context) -
        ScreenUtils.getStatusBarH(context) -
        ScreenUtils.getBottomBarH(context) -
        10 -
        15 -
        50 -
        44;
    int margin = 30;
    // if(("01" == _itemBean?.colorflg) && _multiColorList != null && _multiColorList.length != 0){
    //   maxHeight = maxHeight - 103 - 26;
    //   margin = 82;
    // }
    double screenWidth = ScreenUtils.screenW(context) - margin;
    double width;
    double height;
    if (maxHeight / screenWidth <= 16 / 9) {
      width = maxHeight / (16 / 9);
      height = maxHeight;
    } else {
      width = screenWidth;
      height = screenWidth * (16 / 9);
    }


    print("屏幕宽： ${screenWidth}");
    print("屏幕高： ${maxHeight}");
    print("真实宽： ${width}");
    print("真实高： ${height}");
    _loadUrl = getUrl(_itemBean?.htmlurl);
    print("url:$_loadUrl");
    return Container(
      width: width,
      height: height,
      color: ColorConstants.BG_OR_SPLIT_COLOR,
      child: ClipRRect(
        borderRadius: BorderRadius.all(Radius.circular(4)),
        child:
        StringUtils.isNotEmpty(_itemBean?.diypicurl)?
        _toDiyImageWidget():
        Stack(
          children: [
            Opacity(
              opacity: isUrlLoadComplete ? 1 : 0,
              child: WebView(
                initialUrl: _loadUrl,
                javascriptMode: JavascriptMode.unrestricted,
                javascriptChannels: <JavascriptChannel>[
                  _alertJavascriptChannel(context),
                  _clickJavascriptChannel(context),
                  _downloadJavascriptChannel(context),
                ].toSet(),
                onPageFinished: (String url) {
                  print("加载完成\n" + url);
                  if(_multiColorList != null && _multiColorList.length > 0){
                    // String psdJson = json.encode(_multiColorList[0].data);
                    String psdJson = _multiColorList[0].dataJson;
                    _setPsd(psdJson);
                  }

                  setState(() {
                    isUrlLoadComplete = true;
                  });
                  // setState(() {
                  //   _isLoading = false;
                  //   setState(() {
                  //
                  //   });
                  // });
                },
                onWebViewCreated: (controller) {
                  _webViewController = controller;
                },
                onWebResourceError: (error){
                  print("onWebResourceError:" + error.description);
                },
                // gestureRecognizers: Set()
                //   ..add(
                //     Factory<TapGestureRecognizer>(
                //           () => tapGestureRecognizer,
                //     ),
                //   ),
              ),
            ),
            Center(
              child: Visibility(
                visible: !isUrlLoadComplete,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    CircularProgressIndicator(
                      strokeWidth: 2,
                      // valueColor:ColorTween(begin: Colors.white, end: Colors.red[900]).animate(null),
                      // backgroundColor:(topInfo?.PVCnt?.punchcnt ?? 0)==0? Colors.transparent: Colors.white,
                      // value: _value/190,
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Text(
                      "正在加载",
                      style: TextStyle(
                          color: ThemeRepository.getInstance()
                              .getTextBFC2CC_BFC2CC(),
                          fontSize: 10),
                    )
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _toDiyImageWidget(){
    return VgCacheNetWorkImage(_itemBean?.diypicurl ?? "",
      placeWidget: Container(color: ColorConstants.BG_OR_SPLIT_COLOR),
      imageQualityType: ImageQualityType.original,);
  }


  Widget _getHorizontalList() {
    //01多色彩模式
    if("01" != _itemBean?.colorflg || _multiColorList == null || _multiColorList.length == 0){
      return SizedBox();
    }
    return Container(
      height: ((((ScreenUtils.screenW(context) - 15 - 16) / 5.5) * 114) / 60),
      child: GridView.builder(
          padding: EdgeInsets.only(
            left: 15,
            right: 15,
          ),
          itemCount: _multiColorList?.length??0,
          physics: ClampingScrollPhysics(),
          controller: _horizontalController,
          scrollDirection:Axis.horizontal,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 1,
            mainAxisSpacing: 3,
            crossAxisSpacing: 0,
            childAspectRatio: 114 / 60,
          ),
          itemBuilder: (BuildContext context, int index) {
            return _toGridItemWidget(context, _multiColorList?.elementAt(index), index);
          }),
    );
  }


  Widget _toGridItemWidget(
      BuildContext context, AiPosterPsdListBean itemBean, int index) {
    return ClickBackgroundWidget(
      backgroundColor: Colors.transparent,
      behavior: HitTestBehavior.translucent,
      onTap: () {
        // if(_selectIndex != index){
        _selectIndex = index;
        _initPageNotifier?.value = _selectIndex;
        // String psdJson = json.encode(_multiColorList[_selectIndex].data);
        String psdJson = _multiColorList[_selectIndex].dataJson;
        _setPsd(psdJson);
        // }
      },
      child:ValueListenableBuilder(
        valueListenable: _initPageNotifier,
        builder: (BuildContext context, int changedIndex, Widget child){
          return Column(
            children: [
              Visibility(
                visible: index == _selectIndex,
                child: Image(
                  image: AssetImage("images/icon_poster_selected.png"),
                  width: 14,
                  height: 7,
                ),
              ),
              (index == _selectIndex)?SizedBox(height: 4,):SizedBox(height: 11,),
              Container(
                foregroundDecoration: BoxDecoration(
                  border: Border.all(
                      color: (index == _selectIndex)?Color(0XFFFFFFFF):Colors.transparent,
                      width: (index == _selectIndex)? 1:0),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(4),
                  child: Container(
                    height: (((ScreenUtils.screenW(context) - 15 - 16) / 5.5) * 103 / 60) -1,
                    decoration: BoxDecoration(color: Colors.black),
                    child: VgCacheNetWorkImage(
                      itemBean?.cover ?? "",
                      fit: BoxFit.contain,
                      imageQualityType: ImageQualityType.middleDown,
                    ),
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  ///底部确认栏
  Widget _toBottomWidget() {
    double bottomH = ScreenUtils.getBottomBarH(context);
    return Column(
      children: [
        Expanded(
          child: Container(
            color: ColorConstants.BG_OR_SPLIT_COLOR,
          ),
        ),
        Container(
          color: Color(0xFF21263C),
          height: 50,
          child: Row(children: [
            _toCommonWidget("下载", "icon_download_poster", _download),
            Container(
              height: 24,
              width: 1,
              color: Color(0x1AFFFFFF),
            ),
            _toCommonWidget("编辑", "icon_edit_poster", _edit),
            Container(
              height: 24,
              width: 1,
              color: Color(0x1AFFFFFF),
            ),
            _toCommonWidget("分享", "icon_share_poster", _share),
          ]),
        ),
        Container(
          color: Color(0xFF21263C),
          height: bottomH,
          padding: EdgeInsets.only(bottom: bottomH),
        ),
      ],
    );
  }

  ///通用底部item
  Widget _toCommonWidget(String name, String icon, VoidCallback callback) {
    return Expanded(
      child: Container(
        height: 50,
        child: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {
            callback.call();
          },
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.asset(
                "images/${icon}.png",
                height: 22,
                width: 22,
              ),
              SizedBox(
                width: 4,
              ),
              Text(
                name,
                style: TextStyle(
                    fontSize: 13,
                    color: ThemeRepository.getInstance()
                        .getTextMainColor_D0E0F7()),
              )
            ],
          ),
        ),
      ),
    );
  }


  _setPsd(String psdJson){
    if(psdJson.contains("\\r")){
      psdJson = psdJson.replaceAll("\\r", "<br/>");
    }
    if(psdJson.contains("\\n")){
      psdJson = psdJson.replaceAll("\\n", "<br/>");
    }
    String js = "get_data('${psdJson}')";
    print("js:" + js);
    _currentPsd = js;
    _webViewController?.evaluateJavascript(_currentPsd);
  }

  _download() async{
    if(StringUtils.isNotEmpty(_itemBean?.diypicurl)){
      loading(true, msg: "下载中");
      String saveResult =
          await SaveUtils.saveImage(url: _itemBean?.diypicurl);
      if(StringUtils.isNotEmpty(saveResult)){
        loading(false);
        if(saveResult == "保存成功"){
          toast("下载成功");
        }else{
          toast(saveResult);
        }
      }
      return;
    }
    _downloadOrShare = "00";
    loading(true, msg: "下载中");
    _webViewController?.evaluateJavascript('download_poster()');
  }

  _edit() async{
    if("01" == _itemBean?.useflg){
      //如果有终端正在使用
      bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
        title: "提示",
        content: "编辑保存海报后，已投屏海报将同步更新，确定继续？",
        cancelText: "取消",
        confirmText: "确定",
          confirmBgColor: ThemeRepository.getInstance()
              .getPrimaryColor_1890FF());
      if(result??false){
        _editFunction();
      }
      return;
    }
    _editFunction();

  }

  //编辑实际的执行逻辑
  _editFunction()async{
    //intoflg 01播放列表 02资源库 03海报模板库
    if(StringUtils.isEmpty(_loadUrl)){
      _loadUrl = getUrl(_itemBean?.htmlurl);
    }
    String url = _loadUrl.replaceAll("&type=01", "&type=02");
    //01第一次 02非一次性
    String diyPic = await EditAiPosterDetailPage.navigatorPush(context, url,
        _itemBean, "", "03", _currentPsd, "02", id: _itemBean?.id, callback: (String diyPsd){
          _currentPsd = diyPsd;
        });
    if(StringUtils.isNotEmpty(diyPic)){
      bool show = await SharePreferenceUtil.getBool(SP_SAVE_DIY);
      if(show??true && "01" != _itemBean.useflg){
        CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示",
            content: "已保存至手机相册，你也可以点击右上角设置投屏播放",
            cancelText: "不再显示",
            confirmText: "我知道了",
            confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
            onPop: (){
              SharePreferenceUtil.putBool(SP_SAVE_DIY, false);
              RouterUtils.pop(context);
            }
        );
      }else{
        // VgToastUtils.toast(context, "保存成功");
      }

      setState(() {
        canMirror = true;
        showBubble = false;
        _itemBean?.diypicurl = diyPic;
      });
    }
  }

  _share() {
    SharePosterMenuDialog.navigatorPushDialog(context, () {
      _downloadOrShare = "01";
      _shareFlag = "00";
      if(StringUtils.isNotEmpty(_itemBean?.diypicurl)){
        //直接分享图片
        SSDKMap params = SSDKMap()
          ..setGeneral("AI前台App", "海报", null, _itemBean?.diypicurl, "", _itemBean?.diypicurl, "", "", "",
              "", SSDKContentTypes.image);
        _weChatShare(context, params, _shareFlag);
      }else{
        loading(true, msg: "加载中");
        _webViewController?.evaluateJavascript('download_poster()');
        RouterUtils.pop(context);
      }

    }, () {
      _downloadOrShare = "01";
      _shareFlag = "01";
      if(StringUtils.isNotEmpty(_itemBean?.diypicurl)){
        //直接分享图片
        SSDKMap params = SSDKMap()
          ..setGeneral("AI前台App", "海报", null, _itemBean?.diypicurl, "", _itemBean?.diypicurl, "", "", "",
              "", SSDKContentTypes.image);
        _weChatShare(context, params, _shareFlag);
      }else{
        loading(true, msg: "加载中");
        _webViewController?.evaluateJavascript('download_poster()');
        RouterUtils.pop(context);
      }
    });
  }

  _bigImage() {
    _downloadOrShare = "02";
    loading(true, msg: "加载中");
    _webViewController?.evaluateJavascript('download_img()');
  }

  ///切换logo显示js type 01显示  02隐藏
  _toggleLogo(String type) {
    //logoflg 00显示 01不显示
    _webViewController?.evaluateJavascript('logo_show_hide(${type})');
  }


  ///切换地址显示js type 01显示  02隐藏
  _toggleAddress(String type) {
    _webViewController?.evaluateJavascript('address_show_hide(${type})');
  }

  JavascriptChannel _logoJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'uploadComplete',
        onMessageReceived: (JavascriptMessage message) {
          print("收到了js回调");
          print(message.message);
          loading(false);
          // ToastUtils.toast(msg: "已生成", context: context);
        });
  }

  JavascriptChannel _addressJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'uploadComplete',
        onMessageReceived: (JavascriptMessage message) {
          print("收到了js回调");
          print(message.message);
          loading(false);
          // ToastUtils.toast(msg: "已生成", context: context);
        });
  }


  JavascriptChannel _alertJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'uploadComplete',
        onMessageReceived: (JavascriptMessage message) {
          print("收到了js回调");
          print(message.message);
          loading(false);
          // ToastUtils.toast(msg: "已生成", context: context);
        });
  }

  JavascriptChannel _clickJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'clickPoster',
        onMessageReceived: (JavascriptMessage message) {
          print("收到了点击回调");
          _bigImage();
        });
  }

  JavascriptChannel _downloadJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'saveDiyData',
        onMessageReceived: (JavascriptMessage message) async {
          print("下载图片收到了js回调");
          print(message.message);
          if (message != null &&
              StringUtils.isNotEmpty(message.message) &&
              message.message.contains(",")) {
            String base64Str = message.message.split(",")[1];
            if ("00" == _downloadOrShare) {
              //下载
              Future<String> imageResult = SaveUtils.saveImage(base64Url: base64Str);
              imageResult.then((saveResult) {
                if (StringUtils.isNotEmpty(saveResult)) {
                  loading(false);
                  toast(saveResult);
                }
              });
              //intoflg 01播放列表 02资源库 03海报模板库
              _viewModel.downloadSharePoster("", _itemBean?.picid, "03", "01", "");
            } else if ("01" == _downloadOrShare) {
              //分享
              // _weChatShare(context, message.message);
              String imagePath =
              await FileUtils.createFileFromString(base64Str);
              if (StringUtils.isNotEmpty(imagePath)) {
                loading(false);
                SSDKMap params = SSDKMap()
                  ..setGeneral("AI前台App", "海报", [imagePath], "", imagePath, "", "", "", "",
                      imagePath, SSDKContentTypes.image);
                _weChatShare(context, params, _shareFlag);
              }
              //intoflg 01播放列表 02资源库 03海报模板库
              _viewModel.downloadSharePoster(
                  "",
                  _itemBean?.picid,
                  "03",
                  "02",
                  "微信");
            } else if ("02" == _downloadOrShare) {
              //查看大图
              String imagePath =
              await FileUtils.createFileFromString(base64Str);
              if (StringUtils.isNotEmpty(imagePath)) {
                loading(false);
                VgPhotoPreview.single(context, imagePath,
                    loadingImageQualityType: ImageQualityType.middleDown);
              }
            }
          } else {
            toast("下载失败，请重试");
            loading(false);
          }
        });
  }

  String getUrl(String posterUrl) {
    CompanyInfoBean companyInfoBean =  UserRepository.getInstance().userData.companyInfo;
    ComLogoBean logoBean = UserRepository.getInstance().userData.comLogo;
    String name = companyInfoBean?.companynick??"";
    String address = companyInfoBean?.address??"";
    String logo = "";
    bool transFlag = false;
    if(logoBean != null){
      if(StringUtils.isNotEmpty(logoBean.squareTransparentLogo) && "-1" != logoBean.squareTransparentLogo){
        logo = logoBean.squareTransparentLogo;
        transFlag = true;
      }else if(StringUtils.isNotEmpty(logoBean.squareOpaqueLogo) && "-1" != logoBean.squareOpaqueLogo){
        logo = logoBean.squareOpaqueLogo;
      }else{
        if (!StringUtils.isEmpty(
            companyInfoBean?.companylogo ?? "") && ((companyInfoBean?.companylogo ?? "").contains("http://etpic.we17.com") || (companyInfoBean?.companylogo ?? "").contains("https://etpic.we17.com"))) {
          logo = companyInfoBean?.companylogo ?? "";
        }
      }
    }else{
      if (!StringUtils.isEmpty(
          companyInfoBean?.companylogo ?? "") && ((companyInfoBean?.companylogo ?? "").contains("http://etpic.we17.com")  || (companyInfoBean?.companylogo ?? "").contains("https://etpic.we17.com"))) {
        logo = companyInfoBean?.companylogo ?? "";
      }
    }

    String url;
    if (StringUtils.isNotEmpty(logo)) {
      url =
      "$posterUrl?name=${Uri.encodeComponent(name)}&address=${Uri.encodeComponent(address)}&logo=${Uri.encodeComponent(logo)}";
      // url = "http://etpic.we17.com/test/20210617140614_1605.html?downloadflg=01&name=${name}&address=${address}&logo=${logo}";
    } else {
      url =
      "$posterUrl?name=${Uri.encodeComponent(name)}&address=${Uri.encodeComponent(address)}";
      // url = "http://etpic.we17.com/test/20210617140614_1605.html?downloadflg=01&name=${name}&address=${address}";
    }
    //01 浏览模式    02编辑
    url = url + "&type=02";
    url = url + "&t=" + DateTime.now().millisecondsSinceEpoch.toString();
    print("生成的url");
    print(url);
    return url;
    // return "https://m.chuangkit.com/?ivk_sa=1024320u";
  }

  void _weChatShare(BuildContext context, SSDKMap params, String shareFlag) {
    ShareRepository.getInstance().shareImageToWechat(context, params,
        platforms: ("00" == shareFlag)
            ? ShareSDKPlatforms.wechatTimeline
            : ShareSDKPlatforms.wechatSession);
  }
}
